package com.util;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.model.UserPO;
import com.opensymphony.xwork2.ActionContext;

public class Printer {
	private Logger logger;

	public Printer(Class clazz) {
		logger = Logger.getLogger(clazz);
	}

	public void info(String message) {
		
		StringBuffer logBuffer = buildMessage(ServletActionContext.getRequest(),message);
		logger.info(logBuffer.toString());
		logBuffer.setLength(0);
	}

	public void debug(String message) {
		StringBuffer logBuffer = buildMessage(ServletActionContext.getRequest(),message);
		logger.debug(logBuffer.toString());
		logBuffer.setLength(0);
	}

	public void error(String message) {
		StringBuffer logBuffer = buildMessage(ServletActionContext.getRequest(),message);
		logger.error(logBuffer.toString());
		logBuffer.setLength(0);
	}

	private StringBuffer buildMessage(HttpServletRequest request,String message){
		String ip = getIpAddr(ServletActionContext.getRequest());
	 	String userId = getUserId();
	 	StringBuffer logBuffer = new StringBuffer();
	 	logBuffer.append("IP[").append(ip).append("],").append("User[").append(userId).append("]:");
	 	logBuffer.append(message);
	 	return logBuffer;
	}
	private String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	private String getUserId() {
		Map session = ActionContext.getContext().getSession();
		if (session == null) {
			return "";
		}
		UserPO userSession = (UserPO) session.get("userInfo");
		return userSession == null ? "" : userSession.getUser_id();
	}
}
